<template>
  <!-- 外层容器，高度撑满视口 -->
  <el-container style="height: 100vh; flex-direction: column;">
    <!-- 主体内容区 -->
    <el-container>
      <!-- 左侧容器（包含左上、左中） -->
      <el-aside width="1200px" style="display: flex; flex-direction: column; height: 100%;">
        <div class="left-top" style="flex: 1; background: #f5f7fa; margin-bottom: 10px;display: flex;flex-direction: column;justify-content: center;">
          <div>
            <el-row
                v-for="(row, index) in dataGrid"
                :key="index"
                :gutter="20"
                style="margin-bottom: 15px;"
            >
              <el-col
                  v-for="(item, colIndex) in row"
                  :key="colIndex"
                  :span="8"
              >
                <div class="data-block" style="background: white; padding: 15px; border-radius: 4px; box-shadow: 0 2px 12px rgba(0,0,0,0.1)">
                  <div style="display: flex; justify-content: space-between; align-items: center">
                    <span style="color: #606266; font-size: 14px">{{ item.label }}</span>
                    <span style="color: #303133; font-weight: 500">{{ item.value }} 万元</span>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="left-middle" style="flex: 1; background: #e9eef3;">
          <div ref="trendChartRef" style="height: 100%; background: white; border-radius: 4px; padding: 15px"></div>
        </div>
      </el-aside>

      <!-- 右侧主内容区 -->
      <el-main style="padding: 0;">
        <div style="background: #d3dce6; flex:1;  height: 100%;">
          <!-- 添加雷达图容器 -->
          <div ref="radarChartRef" style="height: 100%; background: white; border-radius: 4px; padding: 15px"></div>
        </div>
      </el-main>
    </el-container>

    <!-- 修改后：通过 v-bind 动态绑定 ref -->
    <el-footer style="height: 500px; background: #f5f7fa; margin-top: 10px">
      <div style="height: 100%; padding: 15px; display: flex;">
        <!-- 日常维护饼图 -->
        <div :ref="pieRefs.dailyPie" style="flex:1; height: 100%; background: white; border-radius: 4px; margin-right: 10px"></div>
        <!-- 养护工程饼图 -->
        <div :ref="pieRefs.maintainPie" style="flex:1; height: 100%; background: white; border-radius: 4px; margin-right: 10px"></div>
        <!-- 科技创新饼图 -->
        <div :ref="pieRefs.techPie" style="flex:1; height: 100%; background: white; border-radius: 4px"></div>
      </div>
    </el-footer>

  </el-container>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 生命周期
onMounted(() => {
  fetchGridData();
  initRadarChart();
  initChart();
  initPieCharts();
  fetchRadarData();
  fetchPieData();
});

// 数据定义
const dataGrid = ref([
  [{ label: '合同总金额', value: '加载中...' }],
  [{ label: '日常维护合同', value: '加载中...' }],
  [{ label: '养护工程合同', value: '加载中...' }],
  [{ label: '科技创新合同', value: '加载中...' }]
]);

const apiConfig = [
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getTotalAmount',
    labels: ['合同总金额', '已结算金额', '审计金额']
  },
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getRoutineTotalAmount',
    labels: ['日常维护合同', '已结算金额', '审计金额']
  },
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getYanghuTotalAmount',
    labels: ['养护工程合同', '已结算金额', '审计金额']
  },
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getTechnologyTotalAmount',
    labels: ['科技创新合同', '已结算金额', '审计金额']
  }
];

const trendApis = [
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getAuditTotalAmountYearChange',
    name: '审计金额',
    color: '#5470c6'
  },
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getAuditRoutineTotalAmountYearChange',
    name: '日常维护',
    color: '#91cc75'
  },
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getAuditYanghuTotalAmountYearChange',
    name: '养护工程',
    color: '#fac858'
  },
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getAuditTechnologyTotalAmountYearChange',
    name: '科技创新',
    color: '#ee6666'
  }
];

const radarApis = [
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getRoutineTotalAmount',
    name: '日常维护'
  },
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getYanghuTotalAmount',
    name: '养护工程'
  },
  {
    url: import.meta.env.VITE_APP_BASE_API + '/countMoney/getTechnologyTotalAmount',
    name: '科技创新'
  }
];

const pieApis = [
  {
    apiKey: '日常维护',
    ref: 'dailyPie',
    title: '日常维护'
  },
  {
    apiKey: '养护工程',
    ref: 'maintainPie',
    title: '养护工程'
  },
  {
    apiKey: '科技创新费',
    ref: 'techPie',
    title: '科技创新'
  }
];

// echarts实例
let trendChart = null;
let radarChartInstance = null;

const radarData = ref({
  indicators: [
    { name: '日常维护', max: 25000 },
    { name: '养护工程', max: 25000 },
    { name: '科技创新', max: 25000 }
  ],
  values: [23429.56, 11928.69, 63.00]
});

const pieData = ref({
  daily: [],
  maintain: [],
  tech: []
});

const trendChartRef = ref();
const radarChartRef = ref();
const pieRefs = {
  dailyPie: ref(),
  maintainPie: ref(),
  techPie: ref()
};

// 金额格式化
function formatAmount(value) {
  return Number(value).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
}

// 获取数据表格
async function fetchGridData() {
  try {
    const requests = apiConfig.map(config =>
        axios.get(config.url).then(res => ({
          config,
          data: res.data.data
        }))
    );
    const results = await Promise.all(requests);
    dataGrid.value = results.map(({ config, data }) => [
      { label: config.labels[0], value: formatAmount(data.totalAmount) },
      { label: config.labels[1], value: formatAmount(data.settlementAmount) },
      { label: config.labels[2], value: formatAmount(data.auditAmount) }
    ]);
  } catch (err) {
    console.error('数据获取失败:', err);
    ElMessage.error('关键指标加载失败，请检查网络连接');
  }
}

// 趋势图
async function initChart() {
  trendChart = echarts.init(trendChartRef.value);
  trendChart.showLoading();

  try {
    const responses = await Promise.all(
        trendApis.map(api =>
            axios.get(api.url).then(res => ({
              name: api.name,
              color: api.color,
              data: res.data.data
            }))
        )
    );

    const allYears = [...new Set(responses.flatMap(res => res.data.map(d => d.year)))].sort();
    const series = responses.map(res => {
      const map = new Map(res.data.map(d => [d.year, d.totalAmount]));
      return {
        name: res.name,
        type: 'line',
        smooth: true,
        symbolSize: 8,
        lineStyle: { width: 3 },
        color: res.color,
        data: allYears.map(year => map.get(year) || 0)
      };
    });

    trendChart.setOption({
      title: {
        text: '合同金额发展趋势（单位：万元）',
        left: 'center',
        textStyle: { color: '#606266' }
      },
      tooltip: {
        trigger: 'axis',
        formatter: params =>
            `${params[0].axisValue}<br>${params.map(p =>
                `${p.marker} ${p.seriesName}: ${p.value} 万元`
            ).join('<br>')}`
      },
      legend: { top: 35 },
      xAxis: {
        type: 'category',
        data: allYears,
        axisLabel: { color: '#606266' }
      },
      yAxis: {
        type: 'value',
        axisLabel: { formatter: value => `${value} 万` }
      },
      series
    });
  } catch (err) {
    console.error('趋势数据获取失败:', err);
    ElMessage.error('趋势数据加载失败');
  } finally {
    trendChart.hideLoading();
  }
}

// 雷达图
async function fetchRadarData() {
  try {
    const requests = radarApis.map(api =>
        axios.get(api.url).then(res => ({
          name: api.name,
          value: res.data.data.totalAmount
        }))
    );
    const results = await Promise.all(requests);
    radarData.value = {
      indicators: results.map(item => ({
        name: item.name,
        max: Math.ceil(item.value * 1.2)
      })),
      values: results.map(item => item.value)
    };
    updateRadarChart();
  } catch (err) {
    console.error('雷达图数据获取失败:', err);
    ElMessage.error('雷达图数据加载失败');
  }
}

function initRadarChart() {
  radarChartInstance = echarts.init(radarChartRef.value);
  radarChartInstance.showLoading();

  radarChartInstance.setOption({
    title: {
      text: '合同金额分布雷达图',
      left: 'center',
      textStyle: { color: '#606266', fontSize: 24 }
    },
    tooltip: {
      trigger: 'item',
      formatter: params => `${params.name}<br/>金额: ${params.value} 万元`
    },
    radar: {
      shape: 'polygon',
      splitNumber: 4,
      name: {
        textStyle: {
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      axisLine: { lineStyle: { color: '#DCDFE6' } },
      splitArea: {
        areaStyle: {
          color: ['rgba(84,112,198,0.05)', 'rgba(84,112,198,0.1)']
        }
      },
      indicator: radarData.value.indicators
    },
    series: [{
      type: 'radar',
      data: []
    }]
  });
}

function updateRadarChart() {
  if (!radarChartInstance) return;
  radarChartInstance.setOption({
    radar: { indicator: radarData.value.indicators },
    series: [{
      data: [{
        value: radarData.value.values,
        name: '合同金额分布'
      }]
    }]
  });
  radarChartInstance.hideLoading();
  window.addEventListener('resize', handleRadarResize);
}

function handleRadarResize() {
  if (radarChartInstance) {
    radarChartInstance.resize();
  }
}

// 饼图
async function fetchPieData() {
  try {
    const { data } = await axios.get(import.meta.env.VITE_APP_BASE_API + '/countMoney/categoryStatistics');
    pieData.value = formatPieData(data.data);
    updatePieCharts();
  } catch (err) {
    console.error('饼图数据获取失败:', err);
    ElMessage.error('分类数据加载失败');
  }
}

function formatPieData(raw) {
  return Object.keys(raw).reduce((acc, key) => {
    acc[key] = Object.entries(raw[key])
        .filter(([_, value]) => value > 0)
        .map(([name, value]) => ({ name, value }))
        .sort((a, b) => b.value - a.value);
    return acc;
  }, {});
}

function updatePieCharts() {
  pieApis.forEach(config => {
    const chart = echarts.init(pieRefs[config.ref].value);
    chart.setOption(getPieOption(config.title));
  });
}

function getPieOption(title) {
  return {
    title: {
      text: `${title}各小类占比`,
      left: 'center',
      textStyle: { fontSize: 18 }
    },
    tooltip: {
      trigger: 'item',
      formatter: ({ name, value, percent }) =>
          `${name}<br>数量: ${value}个 (${percent}%)`
    },
    series: [{
      name: title,
      type: 'pie',
      radius: ['35%', '60%'],
      data: pieData.value[title],
      label: { show: false },
      emphasis: {
        label: { show: true, fontSize: 18 }
      }
    }]
  };
}

function initPieCharts() {
  initSinglePie('dailyPie', pieData.value.daily, '日常维护');
  initSinglePie('maintainPie', pieData.value.maintain, '养护工程');
  initSinglePie('techPie', pieData.value.tech, '科技创新');
}

function initSinglePie(refName, data, title) {
  const chart = echarts.init(pieRefs[refName].value);
  const option = {
    title: {
      text: `${title}中各小类占比`,
      left: 'center',
      top: '5%',
      textStyle: {
        color: '#606266',
        fontSize: 24
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}万元 ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 30,
      bottom: 20,
      textStyle: { color: '#606266' }
    },
    series: [{
      name: title,
      type: 'pie',
      radius: ['35%', '60%'],
      center: ['40%', '55%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 6,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: { show: false },
      emphasis: {
        label: {
          show: true,
          fontSize: 24,
          formatter: '{b}\n{d}%'
        }
      },
      labelLine: { show: false },
      data: data.sort((a, b) => b.value - a.value)
    }],
    color: ['#5470c6','#91cc75','#fac858','#ee6666','#73c0de','#3ba272','#fc8452','#ea7ccc']
  };
  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
}



onBeforeUnmount(() => {
  if (trendChart) echarts.dispose(trendChart);
  if (radarChartInstance) echarts.dispose(radarChartInstance);
  Object.keys(pieRefs).forEach(ref => {
    if (pieRefs[ref].value) echarts.dispose(echarts.getInstanceByDom(pieRefs[ref].value));
  });
  window.removeEventListener('resize', handleRadarResize);
});
</script>




<style scoped lang="scss">

</style>

